/**
 * Created by xiexb on 2017/9/12.
 */

/**
 * 通用功能
 */
var commonUtils = {
    isLoadingCount: 0,
    /**
     * 错误 异常信息显示
     * @param error 错误信息
     */
    showError: function (error) {
        alert(error);
    },
    /**
     * 信息显示
     * @param msg
     */
    showMessage: function (msg) {
        alert(msg);
    },
    /**
     * 统一处理错误信息，错误码
     * @param output
     */
    outPut: function (output, callback) {
        var o = output;
        if (typeof(output) != "object") {
            try {
                o = eval("(" + output + ")");
            }
            catch (exception) {
                //commonUtils.showError("output 在转换成对象时候出差：" + exception);
                return;
            }
        }

        if (o == null || o == undefined) {
            //commonUtils.showError("返回对象为空！");
            return
        }
        if (o.errorCode == -1001) {
            window.location.href = "/index.jsp";
        }
        else if (o.errorCode != 0 || !commonUtils.stringIsNullOrWhiteSpace(o.errorMessage)) {
            //commonUtils.showError(o.errorMessage);
        }
        else {
            callback(o.data);
        }
    },
    /**
     * 显示Loading
     */
    mapLoadingShow: function () {
        $(".tide-data").loading();
    },
    /**
     * 隐藏Loading
     */
    mapLoadingHide: function () {
        $(".tide-data").loading("close");
    },
    /**
     * 显示Loading  以计数器的方式控制 计数器加1
     */
    isLoadingAddCount: function () {
        if (commonUtils.isLoadingCount == 0) {
            commonUtils.mapLoadingShow();
        }
        commonUtils.isLoadingCount = commonUtils.isLoadingCount + 1;
    },
    /**
     * Loading 计算减1 如果计数器为0  就关闭Loading
     */
    isLoadingSunCount: function () {
        commonUtils.isLoadingCount = commonUtils.isLoadingCount - 1;
        if (commonUtils.isLoadingCount <= 0) {
            commonUtils.mapLoadingHide();
            commonUtils.isLoadingCount = 0;
        }
    },
    /**
     * 判断字符串是否为空 undefined null ""
     * @param str 需要判断的字符串
     * @returns {undefined、null、 "" 返回true 其他返回false }
     */
    stringIsNullOrWhiteSpace: function (str) {
        if (str == undefined || str == null || str == "" || str.length == 0) {
            return true;
        } else {
            return false;
        }
    },
    /**
     * 打开窗口 用来下载文件 等
     * @param url
     * @param target
     */
    windowOpen: function (url, target) {
        var a = document.createElement("a");
        a.setAttribute("href", url);
        if (target == null) {
            target = '';
        }

        a.setAttribute("target", target);
        document.body.appendChild(a);
        if (a.click) {
            a.click();
        } else {
            try {
                var evt = document.createEvent('Event');
                a.initEvent('click', true, true);
                a.dispatchEvent(evt);
            } catch (e) {
                window.open(url);
            }
        }
        document.body.removeChild(a);
    },
    /**
     * 获取URL参数
     */
    getQueryString: function (key) {
        var reg = new RegExp("(^|&)" + key + "=([^&]*)(&|$)", "i");
        var r = window.location.search.substr(1).match(reg);
        if (r != null) return (r[2]);
        return null;
    },
    /**
     * 生成KeyValse 形式的list 的列表
     * @param keyValues
     * @returns {*|jQuery|HTMLElement}
     */
    createKeyValueList: function (keyValues) {
        /*var content = "<ul class='panel-list'>";
         if (keyValues == null || keyValues == undefined || keyValues.length == 0) {
         content += "<div>无数据</div>";
         }
         else {
         content += "<table class='table'>";

         for (var i = 0; i < keyValues.length; i++) {
         var keyvalue = keyValues[i];
         content += "<tr>";
         content += "    <td align='right'>";
         content += "        <span class='list-label'>" + keyvalue.id + ":</span>";
         content += "    <td>";
         content += "    <td  align='left'>";
         content += "        <span>" + keyvalue.name + "</span>";
         content += "    <td>";
         content += "</tr>";
         }

         content += "</table>";
         }
         content += "</ul>";
         var div = $(content);
         return div;*/

        var content = "<div class='pop-content'>";
        content += "<div class='form-hor-cont'>";
        content += "	<div class='form-horizontal text-align-lr' style='width: 300px;'>";

        if (keyValues == null || keyValues == undefined || keyValues.length == 0) {
            content += "<div>无数据</div>";
        } else {
            content += "<div class='form-group'>";
            for (var i = 0; i < keyValues.length; i++) {
                var keyvalue = keyValues[i];
                content += "<label class='col-sm-7 control-label'>" + keyvalue.id + "</label>";
                content += "<div class='col-sm-5'><p class='form-control-static'>" + keyvalue.name + "</p></div>";
            }
            content += "</div>";
        }

        content += "	</div>";
        content += "	</div>";
        content += "</div>";
        var div = $(content);
        return div;

    }
};

//获取单个监测站的信息
function loadStationTideData() {
    //var stationname = commonUtils.getQueryString("stationname");
    var stationname = commonUtils.getQueryString("para1");
    if (!commonUtils.stringIsNullOrWhiteSpace(stationname)) {
        stationname = decodeURIComponent(stationname);
    }

    $.ajax({
        url: "/tide/gettidestationnamekpi",
        data: {stationname: stationname},
        dataType: "json",
        async: true,
        type: "GET",
        beforeSend: function () {
            commonUtils.isLoadingAddCount();
        },
        success: function (req) {
            commonUtils.outPut(req, function (datas, station) {
                bandStationTideData(datas);
            });
        },
        complete: function () {
            commonUtils.isLoadingSunCount();
        },
    });
}

function bandStationTideData(data) {
    //潮汐表
    var station = data.station;
    //绑定基础信息
    var titleDim = $("#tide-station-detail-title").empty();
    var title = "港口名称:<span>" + station.stationName + "(" + data.dateKey + ")</span>";
    titleDim.html(title);
    //潮汐数据
    bandTideData(data);

    //潮汐折线图
    try {
        var dataHours = data.tideDataHours;
        bandTideDataHours(dataHours);
    }
    catch (e) {
    }
    bandTipStationWeatherData(data);
}

function bandTideData(data) {
    var table = $("#tide-data-day-table").empty();
    var timeDim = $("#tide-data-day-other").empty();
    //绑定表格
    var time_row = "<tr><td class='f-b'>潮时(Hrs)</td>";
    var data_row = "<tr><td class='f-b'>潮高(cm)</td>";
    if (data.tideDataDay.tideLst != null && data.tideDataDay.tideLst.length > 0) {
        for (var i = 0; i < data.tideDataDay.tideLst.length; i++) {
            time_row += "<td>" + data.tideDataDay.tideLst[i].id + "</td>";
            data_row += "<td>" + data.tideDataDay.tideLst[i].name + "</td>";
        }
    }
    else {
        time_row += "<td>无数据</td>";
        data_row += "<td>无数据</td>";
    }
    time_row += "</tr>";
    data_row += "</tr>"
    table.append($(time_row + data_row));
    //绑定时区
    var t = "<tr><td colspan='5' class='sp-td' style='font-size:10px;'>";
    t += "时区:<span class='m-r-10'>" + data.tideDataDay.timeZone + " </span>   潮高基准面：" + data.tideDataDay.tideDatum;
    t += "</td></tr>";
    table.append($(t));
}

function bandTideDataHours(dataHours) {
    var xAxis_data = [];
    var series_data = [];
    for (var i = 0; i < dataHours.length; i++) {
        xAxis_data.push(dataHours[i].hourKey + "时");
        series_data.push(dataHours[i].timeHeight);
    }
    var option = {
        tooltip: {
            trigger: 'axis'
        },
        grid: {
            x: 45,
            y: 5,
            x2: 2,
            y2: 30
        },
        calculable: true,
        xAxis: [
            {
                show: true,
                type: 'category',
                boundaryGap: false,
                axisLabel: {
                    show: true,
                    textStyle: {
                        color: '#528CCF'
                    }
                },
                splitLine: {
                    show: true,
                    lineStyle: {
                        color: '#528CCF'
                    }
                },
                data: xAxis_data
            }
        ],
        yAxis: [
            {
                type: 'value',
                axisLabel: {
                    formatter: '{value}cm',
                    textStyle: {
                        color: '#528CCF'
                    }
                },
                splitLine: {
                    show: true,
                    lineStyle: {
                        color: '#2A597D'
                    }
                }
            }
        ],
        series: [
            {
                name: '潮高(CM)',
                type: 'line',
                itemStyle: {
                    normal: {
                        color: '#528CCF',
                        lineStyle: {
                            color: '#2E74A6'
                        }
                    }
                },
                data: series_data
            }
        ]
    };
    requiretx(
        [
            'echarts',
            'echarts/chart/line' // 使用柱状图就加载bar模块，按需加载
        ],
        function (ec) {
            // 基于准备好的dom，初始化echarts图表
            var myChart = ec.init(document.getElementById('tide-data-hour-line'));
            myChart.setOption(option);
        }
    );
}

function bandTipStationWeatherData(data) {
    var ul = $("#tide-ul-weather-item").empty();
    $(".mete-data").find("#tide-nodata-msg").remove();
    var weathers = data.tideWeatherOneDay;
    if (weathers == null || weathers.length == 0) {
        $(".mete-cont").hide();
        var div = "<div id='tide-nodata-msg' style='width: 280px; margin: 0 auto;'>暂不提供该时间内天气数据服务</div>";
        $(".mete-data").append($(div));
        return;
    }

    $(".mete-cont").show();
    $("#tide-ul-weather-item").css("left", "0px");
    for (var i = 0; i < weathers.length; i++) {
        var weather = weathers[i];
        var content = "<li index='" + i + "'>"
        if (i == 0) {
            content = "<li index='" + i + "' current='true'>"
        }
        content += "<span class='on-arrow' style='display: none;'></span>"
        content += "<p>" + weather.timeLable + "</p>"
        content += "<p>" + weather.weatherLable + "</p>"
        content += "<p><img src='/css/modules/tide/img/c-weather-ico/" + weather.weather + ".png' width='30'></p>";
        content += "<p>" + weather.temp + "°C</p>"
        content += "<p>风速：" + weather.winS + "m/s</p>"
        content += "<p>风向：" + weather.winD + "°</p>"
        if (weather.dataType == 1) {
            content += "<p>实况</p>"
        }
        else {
            content += "<p>预报</p>"
        }
        content += "</li>";
        ul.append($(content));
    }
}

function moveTipStationSeatherItem(d, time) {
    if (time == undefined) {
        time = 400;
    }
    var ul = $("#tide-ul-weather-item");
    var lis = $("#tide-ul-weather-item").find("li");
    if (lis.length <= 0) {
        return;
    }
    var off_width = $(lis[0]).width() + 7;
    var currentIndex = 0; //lis.index("[current=true]");
    for (currentIndex = 0; currentIndex <= lis.length; currentIndex++) {
        var current = $(lis[currentIndex]).attr("current");
        if (current != undefined && current == "true") {
            break;
        }
    }
    if (d == "next") {
        var flat = lis.length - currentIndex > 7;
        var currentli = lis.get(currentIndex);
        currentIndex = currentIndex + 1;
        var left = off_width * currentIndex * -1;
        var li = lis.get(currentIndex);
        ul.animate({left: left - 7}, time, function () {
            if (!flat) {
                ul.animate({left: left + off_width - 7}, 100);
            }
        });
        if (flat) {
            $(li).attr("current", "true");
            $(currentli).removeAttr("current");
        }
    }
    else {
        var flat = currentIndex > 0;
        var currentli = lis.get(currentIndex);
        currentIndex = currentIndex - 1;
        var left = off_width * currentIndex * -1;
        var li = lis.get(currentIndex);
        ul.animate({left: left - 7}, time, function () {
            if (!flat) {
                ul.animate({left: left - off_width - 7}, 100);
            }
        });
        if (flat) {
            $(currentli).removeAttr("current");
            $(li).attr("current", "true");
        }

    }
};

$(function () {
    //时间左右移动
    $(".front-scroll-ico").click(function () {
        moveTipStationSeatherItem("back");
    });
    $(".back-scroll-ico").click(function () {
        moveTipStationSeatherItem("next");
    });
    $('#tide-ul-weather-item').bind('mousewheel', function (event, delta) {
        var dir = delta > 0 ? 'Up' : 'Down';
        if (dir == 'Up') {
            moveTipStationSeatherItem("back", 200);
        } else {
            moveTipStationSeatherItem("next", 200);
        }
        return false;
    });
    loadStationTideData();
})